from django import http
from django.core.paginator import Paginator
from django.shortcuts import render, redirect
from django.views import View
from courses.models import *

# 由于开发进度不统一，
# 为了能运行，以下是临时代码
from utils import constants


class CoursesView(View):
    """
    课程视图
    """

    def get(self, request):
        """
        返回课程页面
        :param request:
        :return:
        """
        # 获取课程查询集
        courses = Course.objects.all().order_by('-click_nums')
        hot_courses = courses[0:3]
        # 获取当前页
        pageNum = request.GET.get('page', 1)
        # 定义分页器
        # 创建分页器：每页N条记录
        paginator = Paginator(courses, constants.COURSE_LIST_LIMIT)
        # 获取每页商品数据
        try:
            all_courses = paginator.page(pageNum)
        except:
            # 如果page_num不正确，默认给用户404
            return http.HttpResponseNotFound('empty page')
        all_courses.pages = [i for i in range(1, paginator.num_pages + 1)]
        return render(request, 'course-list.html', {'all_courses': all_courses, 'hot_courses': hot_courses})


class CoursesDetailView(View):
    """
    课程详情页展示
    """

    def get(self, request,pk):
        try:
            course = Course.objects.get(id=pk)
        except:
            redirect('/courses/')

        return render(request, 'course-detail.html',{'course':course})
